<template>
    <div class="app-container backorder_page">
        <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form-new" label-width="80px">
            <el-form-item label="订单号" prop="orderNo">
                <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable />
            </el-form-item>
            <el-form-item label="订单状态" prop="orderStatus">
                <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable filterable>
                    <el-option label="交易中" :value="1" />
                    <el-option label="交易取消" :value="2" />
                    <el-option label="交易完成" :value="3" />
                </el-select>
            </el-form-item>


            <el-form-item label-width="60px" label="买家" prop="buyerId">
                     <virtual-select
                    v-model="queryParams.buyerId"
                    :list="allUsers"
                    label="_showLabel"
                    value="userId"
                    :placeholder="'输入关键字用于搜索买家'"
                    :keeps-params="20"
                    :is-concat="false"
                    :concat-symbol="' || '"
                    :is-multiple="false"
                    :disabled="false"
                    :allow-create="false"
                     />
                
            </el-form-item>
            <el-form-item label-width="60px" label="卖家" prop="sellerId">
                <virtual-select
                    v-model="queryParams.sellerId"
                    :list="allUsers"
                   label="_showLabel"
                    value="userId"
                    :placeholder="'输入关键字用于搜索卖家'"
                    :keeps-params="20"
                    :is-concat="false"
                    :concat-symbol="' || '"
                    :is-multiple="false"
                    :disabled="false"
                    :allow-create="false"
                     />

                <!-- <el-select class="bumen" collapse-tags filterable clearable v-model="queryParams.sellerId"
                    placeholder="请选择卖家">
                    <el-option v-for="(item, key) in allUsers" :key="key" :label="item.nickName" :value="item.userId" />
                </el-select> -->
            </el-form-item>

            <el-form-item label-width="60px" label="客服" prop="customerId">
                <el-select class="bumen" collapse-tags filterable clearable v-model="queryParams.customerId"
                    placeholder="请选择客服">
                    <el-option v-for="(item, key) in yuangongList" :key="key" :label="item.nickName"
                        :value="item.userId" />
                </el-select>
            </el-form-item>

            <el-form-item label="游戏账号" prop="account">
                <el-input v-model="queryParams.account" placeholder="请输入游戏账号" clearable />
            </el-form-item>
            <el-form-item label="游戏名称" prop="gameId">
                <el-select v-model="queryParams.gameId" placeholder="请选择游戏" clearable>
                    <el-option v-for="dict in gameList" :key="dict.id" :label="dict.name" :value="dict.id" />
                </el-select>
            </el-form-item>

            <el-form-item label="换绑状态" prop="bindingStatus">
                <el-select v-model="queryParams.bindingStatus" placeholder="请选择换绑状态" clearable filterable>
                    <el-option label="未换绑" :value="1" />
                    <el-option label="已换绑" :value="2" />
                    <!-- <el-option label="换绑成功" :value="3" />
                      <el-option label="换绑失败" :value="4" /> -->
                </el-select>
            </el-form-item>


            <el-form-item label="支付状态" prop="paymentStatus">
                <el-select v-model="queryParams.paymentStatus" placeholder="请选择支付状态" clearable filterable>
                    <el-option label="未支付" :value="1" />
                    <el-option label="已支付" :value="2" />
                    <el-option label="支付失败" :value="3" />
                </el-select>
            </el-form-item>


            <el-form-item label="放款状态" prop="loanStatus">
                <el-select v-model="queryParams.loanStatus" placeholder="请选择放款状态" clearable filterable>
                    <el-option label="未放款" :value="1" />
                    <el-option label="已放款" :value="2" />
                    <el-option label="放款失败" :value="3" />
                </el-select>
            </el-form-item>
            <el-form-item label="合同状态" prop="contractStatus">
                <el-select v-model="queryParams.contractStatus" placeholder="请选择合同状态" clearable filterable>
                    <el-option label="未签署" :value="1" />
                    <el-option label="签署中" :value="2" />
                    <el-option label="已签署" :value="3" />
                </el-select>
            </el-form-item>

            <el-form-item label="售后状态" prop="afterStatus">
                <el-select v-model="queryParams.afterStatus" placeholder="请选择售后状态" clearable filterable>
                    <el-option label="无售后" :value="0" />
                    <el-option label="待处理" :value="1" />
                    <el-option label="已同意" :value="2" />
                    <el-option label="已拒绝" :value="3" />
                </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime">
                <el-date-picker clearable v-model="createTime" value-format="yyyy-MM-dd" type="daterange"
                    range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="完成时间" prop="finishTime">
                <el-date-picker v-model="finishTime" value-format="yyyy-MM-dd" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker>
            </el-form-item>

            <el-form-item class="btns">
                <el-button type="primary" icon="el-icon-search" @click="search" class="zdy-btn">搜索</el-button>
                <el-button icon="el-icon-refresh" type="warning" plain @click="resetQuery">重置</el-button>

                <el-button type="primary" icon="el-icon-plus" v-hasPermi="['interOrder:add']" @click="openCreate"
                    class="zdy-btn">创建中介订单</el-button>


            </el-form-item>
        </el-form>
        <div class="table_box table_box_new">
            <el-table :data="tableData.records" border stripe v-loading="loading">
                <el-table-column prop="orderNo" label="订单号" min-width="140"></el-table-column>
                <el-table-column prop="orderStatus" label="订单状态" min-width="120">
                    <template slot-scope="scope">
                        <el-tag :type="orderStatusType(scope.row.orderStatus)">{{ orderStatusText(scope.row.orderStatus)
                        }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" min-width="160"></el-table-column>
                <el-table-column prop="buyerNickname" label="买家" min-width="120"></el-table-column>
                <el-table-column prop="sellerNickname" label="卖家" min-width="120"></el-table-column>
                <el-table-column prop="customerNickname" label="客服" min-width="120"></el-table-column>
                <el-table-column prop="gameName" label="游戏" min-width="120"></el-table-column>
                <el-table-column prop="account" label="账号" min-width="140" show-overflow-tooltip></el-table-column>
                <el-table-column prop="productAmount" label="商品金额" min-width="110">
                    <template slot-scope="scope">{{ formatMoney(scope.row.productAmount) }}</template>
                </el-table-column>
                <el-table-column prop="compensationFee" label="包赔费" min-width="100">
                    <template slot-scope="scope">{{ formatMoney(scope.row.compensationFee) }}</template>
                </el-table-column>
                <el-table-column prop="serviceFee" label="手续费" min-width="100">
                    <template slot-scope="scope">{{ formatMoney(scope.row.serviceFee) }}</template>
                </el-table-column>
                <el-table-column prop="totalAmount" label="总金额" min-width="110">
                    <template slot-scope="scope">{{ formatMoney(scope.row.totalAmount) }}</template>
                </el-table-column>
                   <el-table-column prop="paymentScreenshot" label="支付截图" min-width="120">
                    <template slot-scope="scope">
                      <img-box width="50px" :height="50" :img="scope.row.paymentScreenshot"></img-box>
                    </template>
                 </el-table-column>
                 <el-table-column prop="bindingStatus" label="换绑截图" min-width="120">
                    <template slot-scope="scope">
                      <img-box width="50px" :height="50" :img="scope.row.bindingScreenshot"></img-box>
                    </template>
                 </el-table-column>
               
                  <el-table-column prop="bindingStatus" label="放款截图" min-width="120">
                    <template slot-scope="scope">
                      <img-box width="50px" :height="50" :img="scope.row.loanScreenshot"></img-box>
                    </template>
                 </el-table-column>
                <!-- <el-table-column prop="bindingStatus" label="换绑状态" min-width="120">
                    <template slot-scope="scope">
                        <el-tag :type="changeBindType(scope.row.bindingStatus)">{{
                            changeBindText(scope.row.bindingStatus) }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="paymentStatus" label="支付状态" min-width="120">
                    <template slot-scope="scope">
                        <el-tag :type="payStatusType(scope.row.paymentStatus)">{{ payStatusText(scope.row.paymentStatus)
                        }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="loanStatus" label="放款状态" min-width="120">
                    <template slot-scope="scope">
                        <el-tag :type="loanStatusType(scope.row.loanStatus)">{{ loanStatusText(scope.row.loanStatus)
                        }}</el-tag>
                    </template>
                </el-table-column> -->
                <el-table-column prop="contractStatus" label="合同状态" min-width="120">
                    <template slot-scope="scope">
                        <el-tag :type="contractStatusType(scope.row.contractStatus)">{{
                            contractStatusText(scope.row.contractStatus) }}</el-tag>
                    </template>
                </el-table-column>

                <el-table-column prop="afterStatus" label="售后状态" min-width="120">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.afterStatus" :type="afterStatusType(scope.row.afterStatus)">{{
                            afterStatusText(scope.row.afterStatus) }}</el-tag>
                    </template>
                </el-table-column>


                <el-table-column prop="finishTime" label="完成时间" min-width="160"></el-table-column>

                <el-table-column prop="cancelReason" label="取消原因" min-width="160"
                    show-overflow-tooltip></el-table-column>

                <el-table-column fixed="right" label="操作" min-width="340">
                    <template slot-scope="scope">
                        <!-- 交易中 -->
                         <el-button type="add" @click="openOrderDetail(scope.row)" v-if="checkPermi(['interOrder:see'])">查看</el-button>
                        <template v-if="scope.row.orderStatus == 1">
                            <el-button type="text" v-hasPermi="['interOrder:edit']"
                                @click="openEdit(scope.row)">编辑</el-button>
                            <el-button type="add" v-if="checkPermi(['interOrder:finish'])"
                                @click="finishOrder(scope.row)">完成订单</el-button>
                            <el-button type="del" v-if="checkPermi(['interOrder:cancel'])"
                                @click="cancelOrder(scope.row)">取消订单</el-button>
                            <el-button type="edit" @click="openBaopeiData(scope.row)"
                                v-if="checkPermi(['interOrder:baopeiziliao'])">包赔资料</el-button>
                        </template>
                        <!-- 交易完成 -->
                        <template v-else-if="scope.row.orderStatus == 3">
                            
                            <el-button type="text" v-if="checkPermi(['interOrder:afterSale']) && scope.row.afterStatus != 1"
                                @click="openAfterSale(scope.row)">发起售后</el-button>
                        </template>

                        <template v-if="scope.row.orderStatus == 3 || scope.row.orderStatus == 1">
                            <el-button type="text"
                                v-if="checkPermi(['interOrder:contract']) && scope.row.contractStatus == 1"
                                @click="createContractChange(scope.row)">发起合同</el-button>
                         

                                   <el-button type="text" 
                            v-if="checkPermi(['interOrder:group']) && (scope.row.groupStatus == 1||!scope.row.groupStatus)"
                            @click="oneClickGroup(scope.row)">一键拉群</el-button>
                        <el-button type="del"
                            v-if="checkPermi(['interOrder:dismissGroup']) && scope.row.groupStatus == 2"
                            @click="cancelGroupIM(scope.row.id)">解散群组</el-button>
                        <el-button type="text"
                            v-if="checkPermi(['interOrder:recoverGroup']) && scope.row.groupStatus == 3"
                            @click="recoveryGroup(scope.row.id)">恢复群组</el-button>
                        <el-button type="text"
                            v-if="checkPermi(['interOrder:enterGroup']) && scope.row.groupStatus == 2"
                            @click="enterGroup(scope.row)">进入群聊</el-button>
                                
                        </template>
                           <el-button type="add"
                                v-if="checkPermi(['interOrder:contract']) && (scope.row.contractStatus == 2 || scope.row.contractStatus == 3)"
                                @click="openContract(scope.row.contractId)">查看合同</el-button>
                     
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="pages-box">
            <pagination v-show="tableData.total > 0" :total="tableData.total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
        <interOrderEditDialog ref="interOrderEditDialog" @submit="onEditSubmit"></interOrderEditDialog>
        <interOrderDetail ref="interOrderDetail"></interOrderDetail>
        <baopeiEditDialog ref="baopeiEditDialog"></baopeiEditDialog>
         <createContract ref="createContractRef"></createContract>
           <!-- 合同签署详情 -->
    <viewContract ref="viewContract"></viewContract>

    <!-- 发起售后 -->
     <interAfter ref="interAfterRef"></interAfter>
    </div>
</template>
<script>
import gameListApi from "@/api/gameConfig/gameList";
import supplyConfigApi from "@/api/system/supplyConfig";
import interOrderEditDialog from "./components/interOrderEditDialog.vue";
import interOrderDetail from "./components/interOrderDetail.vue";
import baopeiEditDialog from "./components/interBaopei.vue";
import { lagroup, canclegroup, recogroup, cancelOrder, finishOrder, afterCreate } from "@/api/interOrder/index";
import viewContract from "@/views/aiqian/viewContract.vue";

import { getList } from "@/api/interOrder/index";

import createContract from "@/views/aiqian/createContract.vue";
import interAfter from "./components/interAfter.vue";

import VirtualSelect from "@/components/VirtualSelect.vue";


export default {
    components: { VirtualSelect,interAfter,interOrderEditDialog, interOrderDetail, baopeiEditDialog ,createContract ,viewContract },
    data() {
        return {
            gameList: [],

            createTime: [],
            finishTime: [],
            queryParams: {
                orderNo: '',
                orderStatus: '',
                buyerId: '',
                sellerId: '',
                customerId: '',
                account: '',
                gameId: '',
                bindingStatus: '',
                paymentStatus: '',
                loanStatus: '',
                contractStatus: '',
                afterStatus: '',
                pageNum: 1,
                pageSize: 10,
            },
            yuangongList: [],
            allUsers: [],
            tableData: { records: [], total: 0 },
            loading: false,
            laqunLoading: false , 
            items: []
        };
    },
    mounted() {
         this.getData()
        this.getYuangongList();
        this.getAllUsers()
        this.getGameList();
        this.getList();
    },

    methods: {
        getData () {
        for (let i = 0; i < 200000; i++) {
          this.items.push({ title: 'muzidigbig' ,id : i})
        }
      },
        // 游戏列表
        getGameList() {
            gameListApi.getGameList().then((res) => {
                this.gameList = res.rows;
            });
        },
        getAllUsers() {
            supplyConfigApi.getAllUserList().then((res) => {

                this.allUsers = res.rows || [];
                this.allUsers = res.rows .map(u => ({
  ...u,
  _showLabel: `${u.nickName}(${u.phonenumber})`   
}))
            });
        },
        // 获取所有员工列表
        getYuangongList() {
            supplyConfigApi
                .getAllUserList({
                    userNewType: 1,
                })
                .then((res) => {
                    this.yuangongList = res.rows;
                });
        },

        // 列表
        getList() {
            this.loading = true;
            this.queryParams = this.addDateRange(this.queryParams, undefined, {
                CreateTime: this.createTime,
                FinishTime: this.finishTime
            })
            getList(this.queryParams).then((res) => {
                this.tableData = { records: res.rows, total: res.total };
                this.loading = false;
            });

        },

        search() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        //重置
        resetQuery() {
            this.$nextTick(() => {
                this.$refs.queryForm.resetFields();
                this.createTime = [];
                this.finishTime = [];
                this.getList();
            });

         
        },

        openCreate() {
            this.$refs.interOrderEditDialog.open('add')
        },
        onEditSubmit() {
            this.getList();
        },
        // 操作区方法占位
        openEdit(row) {
            this.$refs.interOrderEditDialog.open('edit', row)
        },
        createContractChange(row) { 
           this.$refs.createContractRef.open(row,3);
         },
        openContract(contractId) {
             if (!contractId) { this.$message.warning('无合同'); return; } 
            this.$refs.viewContract.open(contractId);
            
            },
        finishOrder(row) {
              let str = ''
      if(!row.paymentScreenshot){
        str = str +'支付截图,'
      }
      if(!row.bindingScreenshot){
        str = str +'换绑截图, '
      }
      if(!row.loanScreenshot){
        str = str +'放款截图, '
      }
      if(str){
        str ='当前订单'+  str+ '未上传,请确认该中介订单各方均已完成，完成后不可撤销, 是否继续?'
      }else{
        str = '确定完成订单吗?'
      }
     this.$confirm(
        str,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "",
        }
      )
        .then(() => {
             finishOrder(row.id).then(res => {
               this.$message({
              type: "success",
              message: res.msg,
            });
                this.getList()
            })
        }).catch(() => {});
           
        },
        cancelOrder(row) {
            this.$prompt('请输入取消原因', '取消订单', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputValidator: (value) => {
                    if (!value || value.trim() === '') {
                        return '请填写取消原因';
                    }
                    return true;
                },
            }).then(({ value }) => {
                cancelOrder({
                    id: row.id,
                    cancelReason: value
                }).then(() => {
                    this.$message.success('取消成功');
                    this.getList();
                })
            }).catch(() => {
                // 用户取消操作
                this.$message.info('已取消操作');
            });
        },
        openBaopeiData(row) {
            this.$refs.baopeiEditDialog.open(row, 'edit');
        },
        oneClickGroup(row) {
            const msg = `
                <div>
                    <p>包赔客服：${row.customerNickname || '-'}</p>
                    <p>卖家：${row.sellerNickname || '-'}</p>
                    <p>买家：${row.buyerNickname || '-'}</p>
                </div>
            `
            this.$confirm(msg, '确认一键拉群吗?', { type: 'warning', dangerouslyUseHTMLString: true, confirmButtonText: '确认', cancelButtonText: '取消' })
                .then(() => {
                    let data = {
                        id: row.id,
                        buyerId: row.buyerId,
                        sellerId: row.sellerId,
                        customerId: row.customerId,
                        account: row.account
                    }
                    this.laqunLoading = true
                    lagroup(data).then(res => {
                        this.$message.success('拉群成功')
                        this.getList()
                    }).finally(() => {
                        this.laqunLoading = false
                    })
                })
                .catch(() => { /* 取消 */ })
        },
        cancelGroupIM(id) {
            this.$confirm('确认解散群组？', '提示', { type: "warning" }).then(() => {
                canclegroup(id).then(res => {
                    this.$message.success('已解散群组');
                     this.getList()
                })
               
            }).catch(() => { });
        },


        async recoveryGroup(id) {
            const res =await recogroup(id)
            if (res.code === 200) {
                this.$message.success('已恢复群组');
                this.getList()
            }

        },
        enterGroup(row) {

               // 跳转客服系统
            if(!row.toGroup) {
                this.$message.error('未找到群聊')
                return
            }
                // let token = Cookies.get("Admin-Token");
                let obj = {
                    type: "goChat",
                    hxusername: row.toGroup,
                    chatType: 'groupChat',
                };
                // 告诉IM系统，需要跳转聊天页
                this.$store.dispatch("postMsgToIM", obj);
  
        },
        openOrderDetail(row) {
            this.$refs.interOrderDetail.open(row);
        },
        openAfterSale(row) {
            // 检查是否可以申请售后
            this.$refs.interAfterRef.open(row)
        },

        // 字典渲染
        orderStatusText(val) { const map = { 1: '交易中', 2: '交易取消', 3: '交易完成' }; return map[val] || '-'; },
        orderStatusType(val) {
            switch (val) {
                case 1: return 'warning'; // 交易中
                case 2: return 'danger';  // 交易取消
                case 3: return 'success'; // 交易完成
                default: return 'info';
            }
        },
        changeBindText(val) { const map = { 1: '未换绑', 2: '已换绑' }; return map[val] || '-'; },
        changeBindType(val) {
            switch (val) {

                case 2: return 'success'; // 已换绑
                case 1: return 'info';   // 未换绑
                default: return 'info';
            }
        },
        payStatusText(val) { const map = { 1: '未支付', 2: '已支付', 3: '支付失败' }; return map[val] || '-'; },
        payStatusType(val) {
            switch (val) {
                case 2: return 'success'; // 已支付
                case 1: return 'info';    // 未支付
                case 3: return 'danger';  // 支付失败
                default: return 'info';
            }
        },
        loanStatusText(val) { const map = { 1: '未放款', 2: '已放款', 3: '放款失败' }; return map[val] || '-'; },
        loanStatusType(val) {
            switch (val) {
                case 2: return 'success'; // 已放款
                case 1: return 'info';    // 未放款
                case 3: return 'danger'; // 放款失败
                default: return 'info';
            }
        },
        contractStatusText(val) { const map = { 1: '未签署', 2: '签署中', 3: '已签署', 4: '已作废' }; return map[val] || '-'; },
        contractStatusType(val) {
            switch (val) {
                case 3: return 'success'; // 已签署
                case 2: return 'warning'; // 签署中
                case 4: return 'danger';  // 已作废
                case 1: return 'info';    // 未生成
                default: return 'info';
            }
        },
        afterStatusText(val) { const map = { 1: '待处理', 2: '已同意', 3: '已拒绝' }; return map[val] || '-'; },
        afterStatusType(val) {
            switch (val) {
                case 2: return 'success'; // 已生成
                case 3: return 'danger';  // 已作废
                case 1: return 'info';    // 未生成
                default: return 'info';
            }
        },
        formatMoney(n) { if (n === 0) return '0.00'; if (!n) return '---'; return Number(n).toFixed(2); }
    }
}

</script>
